package ext;

import org.junit.Test;

public class ReverseNumber {
    
    public int reverse(int num) {
        int res = 0;
        boolean flag = true;
        if (num < 0) {
            num = -num;
            flag = false;
        }
        int limit = Integer.MAX_VALUE / 10;
        while (num != 0) {
            int cur = num % 10;
            num /= 10;
            if (res < limit) {
                res = res * 10 + cur;
            } else if (res == limit) {
                if (flag && cur <= 7) {
                    return res * 10 + cur;
                } else if (!flag && cur <= 8) {
                    return -res * 10 - cur;
                } else {
                    return flag ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
            } else {
                return flag ? Integer.MAX_VALUE : Integer.MIN_VALUE;
            }
        }
        return flag ? res : -res;
    }


    @Test
    public void test() {
        System.out.println(reverse(-1234168515));        
    }

}
